import json
import logging
from functools import wraps
from django.template.response import TemplateResponse
from rest_framework.response import Response

# 使用专属的 logging_utils logger，仅输出到 general.log
logger = logging.getLogger('logging_utils')
def log_request_response(view_func):
    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
        # 解析请求体
        if request.content_type == 'application/json':
            try:
                request_data = json.loads(request.body.decode('utf-8'))
            except json.JSONDecodeError:
                request_data = {}
        elif request.method == "POST":
            request_data = request.POST.dict()
        else:
            request_data = request.GET.dict()

        # 过滤敏感信息
        filtered_data = {key: (value if key not in ["password", "token"] else "***") for key, value in
                         request_data.items()}

        logger.debug(f"Request {request.method} {request.path}: {filtered_data}")

        # 调用视图函数
        response = view_func(request, *args, **kwargs)

        # 记录响应
        if isinstance(response, (TemplateResponse, Response)) and response.is_rendered:
            logger.debug(f"Response {response.status_code}: {response.content}")
        else:
            logger.debug(f"Response {response.status_code} (not rendered yet)")

        return response

    return _wrapped_view
